import base64
import re
from fastapi import HTTPException
from app.config.settings import settings


def base64_to_bytes(image_base64: str) -> bytes:
    try:
        # 检查Base64字符串长度
        if len(image_base64) > settings.base64_max_length:
            raise ValueError("Base64 string too long")

        # 去除可能的data URL前缀
        if "," in image_base64:
            image_base64 = image_base64.split(",")[1]

        # 检查Base64有效性
        if not re.match(r"^[A-Za-z0-9+/]+={0,2}$", image_base64):
            raise ValueError("Invalid Base64 string")

        return base64.b64decode(image_base64)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))